<template>
    <div class="textarea-box">
        <div class="textarea-item">
            <textarea ref="response"></textarea>
        </div>
    </div>
</template>

<script>
import format from './format'

export default {
    props: ['file'],
    data() {
        return {
            config: null
        }
    },
    mounted() {
        this.initResponse();
        this.formatResponse();
    },
    methods: {
        initResponse() {
            this.response = this.$CodeMirror.fromTextArea(this.$refs.response, {
                mode: 'text/javascript',
                indentWithTabs: true,
                smartIndent: false,
                lineNumbers: true,
                lineWrapping: true,
                foldGutter: true,
                matchBrackets: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                theme: 'mdn-like',
            });
            this.response.on('beforeChange', (instance, changeObj) => {
                if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
                    var _str = this.response.getSelection();
                    if (_str.toString().length > 0) {
                        this.response.replaceSelection(_str + _str + changeObj.text);
                    };
                };
            });
        },
        formatJson(type) {
            var str = this[type].getValue();
            str = this.beautify(str);
            this[type].setValue(str);
        },
        beautify(source) {
            function looks_like_html(source) {
                var trimmed = source.replace(/^[ \t\n\r]+/, '');
                return trimmed && (trimmed.substring(0, 1) === '<');
            };
            var output,
                opts = {
                    // brace_style : "expand"
                };
            opts.indent_char = ' ';
            opts.preserve_newlines = "-1";
            if (looks_like_html(source)) {
                output = html_beautify(source, opts);
            } else {
                output = js_beautify(source, opts);
            };
            return output;
        },
        formatResponse() {
            if (this.file.responses) {
                var _String = format.String(this.file.responses, this.$bus.getFolder(this.file.parent).models);
                var str = this.beautify(_String);
                this.response.setValue(str);
            };
        },
        setResponse(Data) {
            var _String;
            if (this.file.responses) {
                _String = format.Response(Data, this.file.responses, this.$bus.getFolder(this.file.parent).models);
            } else {
                _String = JSON.stringify(Data);
            }
            var str = this.beautify(_String);
            this.response.setValue(str);
        }
    }
}
</script>

<style>
</style>